import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Button } from 'antd';
import { Synergy } from '../components/Portal/Portal';
import {
  WeaTop,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaDropMenu,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaLocaleProvider,
} from 'ecCom';
import { Spin } from 'antd';
import AddTab from './add/AddTab';
import AddContent from './add/AddContent';
import { message } from 'antd';
import { GetUrlParam } from '../util';

const { addLeaf, getDefautDatasShow, doFavEdit } = WeaLeftTree;
const getLabel = WeaLocaleProvider.getLabel;
@inject('docAddStore')

@observer
class Add extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      queryUrl: {
        isFav: this.props.location.query.isFav || '0',
        isCommon: this.props.location.query.isCommon || '0',
        openNewWindow: this.props.location.query.openNewWindow || '0',
      },
      collectParams:{
        favname: getLabel(1986, '新建文档'),
        favouritetype: 2,
        objid: 0,
        importantlevel: 1,
        link: 'wui/index.html#/main/document/add',
      },
      dropMenuProps:{
        collectParams: {
          favname: getLabel(1986, '新建文档'),
          favouritetype: 2,
          objid: 0,
          importantlevel: 1,
          link: 'wui/index.html#/main/document/add',
        },
      }
    };
  }
  componentDidMount() {
    const { docAddStore, location } = this.props;
    const { getTreeDatas, isWevarSystem } = docAddStore;
    let queryUrl = { isFav: '0', isCommon: '0', openNewWindow: '1' };
    for (let i in location.query) {
      queryUrl[i] = location.query[i];
    }
    let paramssecid = GetUrlParam(location.search, 'secid');
    if (location.search != '' && paramssecid != '') {
      docAddStore.setKey([paramssecid]);
    }
    getTreeDatas(queryUrl);
  }
  componentWillReceiveProps(nextProps) {
    const { docAddStore, location } = nextProps;
    const { getTreeDatas, isWevarSystem } = docAddStore;
    let paramssecid = GetUrlParam(toJS(location.search), 'secid');
      let queryUrl = { isFav: '0', isCommon: '0', openNewWindow: '1' };
      for (let i in location.query) {
        queryUrl[i] = location.query[i];
      }
      if (location.search != '' && paramssecid != '') {
        docAddStore.setKey([paramssecid]);
      }
      getTreeDatas(queryUrl);
  }
  componentWillUnmount() {
  }

  openDialog(flag) {
    if (flag == 1) {
      let documentMarkDialog = new window.top.Dialog();
      documentMarkDialog.currentWindow = window;
      let url = '/docs/docs/document/document2.jsp';
      documentMarkDialog.Title = getLabel('385083', '知识价值链');
      documentMarkDialog.Width = 1200;
      documentMarkDialog.Height = 600;
      documentMarkDialog.Drag = true;
      documentMarkDialog.URL = url;
      documentMarkDialog.show();
    } else if (flag == 2) {
      let documentMarkDialog = new window.top.Dialog();
      documentMarkDialog.currentWindow = window;
      let url = '/docs/docs/document/document.jsp';
      documentMarkDialog.Title = getLabel(385084, '知识结构图');
      documentMarkDialog.Width = 1200;
      documentMarkDialog.Height = 600;
      documentMarkDialog.Drag = true;
      documentMarkDialog.URL = url;
      documentMarkDialog.show();
    }
  }

  getButtons() {
	 const { docAddStore, location } = this.props;
    let { isWevarSystem } = docAddStore;
	if (isWevarSystem == '1') {
		return [
		   { label: getLabel(385083, '知识价值链'), onClick: () => this.openDialog(1) },
		   { label: getLabel(385084, '知识结构图'), onClick: () => this.openDialog(2) },
		];
	}
		return [];
  }
  getShowItem = (tempResult, domid, pid) => {
    let result = [];
    let temp = [];
    tempResult.forEach((item) => {
      if (item.item.domid === domid) {
        result.unshift(item.item);
      }
    });
    tempResult.forEach((item) => {
      if (item.item.key === pid) {
        result.unshift(item.item);
        temp = [];
        if (pid !== '') {
          temp = this.getShowItem(tempResult, item.item.domid, item.item.pid);
          temp.pop();
          result = temp.concat(result);
        }
      }
    });
    return result;
  }
  getItem = (item, selected) => {
    let getNode = false;
    let returnItem = [];
    if (item.domid === selected) {
      getNode = true;
      returnItem.push({ item, getNode });
    } else {
      returnItem.push({ item, getNode });
      if (item.haschild) {
        item.childs.forEach((i) => {
          let tempResult = [];
          tempResult = this.getItem(i, selected);
          returnItem = returnItem.concat(tempResult);
        });
      }
    }
    return returnItem;
  }
  getTree() {
    const { docAddStore } = this.props;
    let {  treeDatas, selectedDomId, companyDropMenu
      , expandedKey, companysDefault } = docAddStore;
    selectedDomId = selectedDomId.toJS();
    return (
      <div className="add-lefttree">
        <WeaDropMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaDropMenu@ahzfcr`} defaultMenu={companysDefault.name}
          dropMenu={companyDropMenu}
          onSelect={this.onDropMenuSelect}
        />
        <div className="add-doc-lefttree">
          <WeaLeftTree ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftTree@uauel2`}
            ref="leftTree"
            showCollect={true}
            datas={toJS(treeDatas)}
            expandedKeys={expandedKey.slice()}
            onExpand={this.onTreeExpand}
            selectedKeys={selectedDomId}
            onSearchLabelClick={this.onSearchLabelClick}
            defaultExpandLevel={0}
            onCollect={this.onTreeCollect}
            onSelect={this.onTreeSelect}
          />
        </div>
      </div>
    );
  }

  onDropMenuSelect=(e) => {
    const { docAddStore, location } = this.props;
    let { getTreeDatas, selectedDomId, setsearchValue, companyDropMenu, openNewWindow
      , setIsTreeNodeEmpty } = docAddStore;
    selectedDomId = selectedDomId.toJS();
    this.refs.leftTree && this.refs.leftTree.setState({ searchValue: '' });
    companyDropMenu.forEach((v) => {
      const item = toJS(v);
      if (e.key === item.companyid) {
        let queryUrl;
        if (e.key === '1') {
          queryUrl = { isFav: '0', isCommon: '0', openNewWindow };
          for (let i in location.query) {
            queryUrl[i] = location.query[i];
          }
          getTreeDatas(queryUrl);
          setIsTreeNodeEmpty(true);
          setsearchValue('');
        } else if (e.key === '2') {
          queryUrl = { isFav: '1', isCommon: '0', openNewWindow };
          for (let i in location.query) {
            queryUrl[i] = location.query[i];
          }
          getTreeDatas(queryUrl);
          setIsTreeNodeEmpty(true);
          setsearchValue('');
        } else if (e.key === '3') {
          queryUrl = { isFav: '0', isCommon: '1', openNewWindow };
          for (let i in location.query) {
            queryUrl[i] = location.query[i];
          }
          getTreeDatas(queryUrl);
          setIsTreeNodeEmpty(true);
          setsearchValue('');
        }
        this.setState({ queryUrl });
      }
    });
  }

  onSearchLabelClick=() => {
    const { docAddStore } = this.props;
    const {clearSelectedDomId,setKey,setsearchValue}=docAddStore;
    clearSelectedDomId();
    setKey([]);
    setsearchValue('');
  }
  onTreeExpand=expandedKey => {
    const { docAddStore } = this.props;
    const {setExpandedKey}=docAddStore;
    setExpandedKey(expandedKey)}
  onTreeSelect=(key, count, countType) => {
    const { docAddStore } = this.props;
    let {  setSelectedDomId, selectedDomId, setsearchValue,  setKey, setIsTreeNodeEmpty, } = docAddStore;
    selectedDomId = selectedDomId.toJS();
    setSelectedDomId(key);
    setKey([countType.node.props.data.key]);
    setsearchValue('');
    setIsTreeNodeEmpty(false);
  }
  onTreeCollect=(data) => {
    const { docAddStore } = this.props;
    let { treeDatas, selectedDomId, expandedKey, setTreeDatas, setExpandedKey } = docAddStore;
    selectedDomId = selectedDomId.toJS();
    const domid = data.domid;
    return new Promise((resolve) => {
      WeaTools.callApi('/api/doc/category/collute', 'GET', {
        operate: data.fav ? 'undo' : 'do',
        secid: data.key,
      }).then((data) => {
        if (data.status === 1) {
          let treeData = doFavEdit(toJS(treeDatas), domid);
          setTreeDatas(treeData);
          data.hasDoFavToDatas = true;
          setExpandedKey(expandedKey.slice());
          resolve(data);
        } else {
          message.warning(data.msg || getLabel(385472, '收藏失败，请重试！'));
        }
      });
    });
  }
  render() {
    const { docAddStore } = this.props;
    const { loadingAdd } = docAddStore;
    const topButtons = this.getButtons();
    return (
      <div className="wea-doc-add">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@r820ei`}
          collectParams={this.state.collectParams}
        >
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@5nwl3t`}
            title={docAddStore.title}
            loading={docAddStore.loadingAdd}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            buttons={topButtons.map(v => <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vbqnxv@CreateDoc`} {...v} type="primary">{v.label}</Button>)}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuProps={this.state.dropMenuProps}
          >
            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@sjqj7f`} isNew={true} leftCom={this.getTree()} >
              <AddTab ecId={`${this && this.props && this.props.ecId || ''}_AddTab@cdo9q6`} />
              <AddContent ecId={`${this && this.props && this.props.ecId || ''}_AddContent@fhmnhe`} queryUrl={this.state.queryUrl} />
            </WeaLeftRightLayout>
          </WeaTop>
        </WeaRightMenu>
        <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@w94pgu`} pathname="/document/add" secid="-1" docid="-1" />
      </div>
    );
  }
}

export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@varer0`} msg={props.error ? props.error : getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' },
)(Add);

